import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_menu/app_config.dart';
import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/biz/update/app_version_update.dart';
import 'package:flutter_menu/gen/assets.gen.dart';
import 'package:flutter_menu/model/app_update_model.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/model/shope_model.dart';
import 'package:flutter_menu/widgets/comm_dialog.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:r_upgrade/r_upgrade.dart';
import 'package:flutter_menu/objectbox.g.dart' as obx;
import 'package:url_launcher/url_launcher.dart';

import '../../data/menu_repository.dart';
import '../../data/obx_store.dart';
import '../../menu_page.dart';

class SettingController extends GetxController {
  List<GVItem> items = [];
  String version = "";
  final MenuRepository _api = Get.find();
  late GVItem versionGv ;

  int process = 0;
  DownStatus status = DownStatus.loading;
  StreamSubscription? listen;
  int? upAppId;
  obx.Admin? admin;
  ShopModel? shopModel;
  AppVersion? _appVersion;
  bool isNeedUpdate = false;


  @override
  void onInit() {
    super.onInit();
    if (obx.Admin.isAvailable()) {
      // Keep a reference until no longer needed or manually closed.
      admin = obx.Admin(store);
    }

    items.add(GVItem("chose_table".tr, MyAssets.images.icTable.path, onTap: choseTable));
    items.add(GVItem("re_menu".tr, MyAssets.images.icReMenu.path, onTap: reMenu));
    items.add(versionGv = GVItem("check_version".tr, MyAssets.images.icCheckVersion.path, onTap: checkVersion));
    items.add(GVItem("logout".tr, MyAssets.images.icLogout.path, onTap: logout));

  }

  @override
  void onReady() {
    super.onReady();
    initShop();
    initVersion();
  }


  void initShop() {
    _api.getShopInfo().then((e) {
      shopModel = e;
      update();
    });
  }

  Future<void> initVersion() async{
    var v =  await PackageInfo.fromPlatform();
    version = v.version;
   var appVersion =  await _api.getAppVersion();
    String newVersion =  appVersion.versionName ??"" ;
    List<String> newVersionList = newVersion.split('.');
    List<String> versionList = version.split('.');
    if (newVersionList.length == 3) {
      for (int index = 0; index < 3; index++) {
        int newVersionCount = int.parse(newVersionList[index]);
        int versionCount = int.parse(versionList[index]);
        if (newVersionCount > versionCount) {
          isNeedUpdate = true;
          versionGv.icon = MyAssets.images.icNotice.path;
          update();
          break;
        } else if (newVersionCount < versionCount) {
          break;
        }
      }
    }
    _appVersion = appVersion;
  }



  void choseTable(GVItem item, int index) {
   Get.toNamed(MenuPages.Menu_Order_Table);
  }

  void reMenu(GVItem item, int index) async {
    try {
      SmartDialog.showLoading();
       await _api.mockSync("");
    }  finally {
      SmartDialog.dismiss();
    }

  }
  void checkVersion(GVItem item, int index)  async{
    if(_appVersion == null){
      await initVersion();
    }else{
      showUpdateDialog();
    }
  }
  void logout(GVItem item, int index) {
    AppConfig.instance.logout();
    Get.find<ShopCarController>().clean();
    Get.offAllNamed(MenuPages.Menu_Login);
  }

  void showUpdateDialog(){
    var info = _appVersion;
    if(info == null) return;
    var submitFc ;
    if(Platform.isAndroid ){
      submitFc = startAppUpdate;
    }else  if(Platform.isIOS){
      submitFc = (){
        launch(info.url!, forceSafariVC: false, forceWebView: false);
      };
    }

    MessageDialog(
      title: "check_version".tr,
      content: "update_desc".tr,
      cancel: info.mandatory?null: BtnModel.cancel(),
      confirm: BtnModel.confirm(title: "update_now".tr,callback: submitFc),
    ).show();
  }


  void startAppUpdate() async{
    var info = _appVersion;
    if(info == null) return;
    String url = "${info.url}";
    String fileName = "${info.versionName}_${DateTime.now().microsecondsSinceEpoch}.apk";
    UpdateWidget().show();
    _listen();
    int? curId   =upAppId;
    var status = curId == null ? null :  await RUpgrade.getDownloadStatus(curId);
    if (status == null ||
        status == DownloadStatus.STATUS_CANCEL ||
        status == DownloadStatus.STATUS_FAILED) {
      upAppId ??= await RUpgrade.upgrade(url, fileName: fileName,installType:RUpgradeInstallType.none);
    }
  }

  void _listen(){
    if(listen != null) return;
    listen = RUpgrade.stream.listen((DownloadInfo info) {
      DownloadStatus? status =  info.status;
      if (status == null ||
          status == DownloadStatus.STATUS_CANCEL ||
          status == DownloadStatus.STATUS_FAILED) {
        this.status = DownStatus.error;
      }else if(status == DownloadStatus.STATUS_RUNNING ){
        this.status = DownStatus.loading;
        process  = info.percent?.toInt()??0;
      }else if(status == DownloadStatus.STATUS_SUCCESSFUL ){
        UpdateWidget().show();
        this.status = DownStatus.complete;
      }
      update(["updateApp"]);
    });
  }


  void retry()async {
    Get.back();
    startAppUpdate();
  }

  void install() {
    RUpgrade.install(upAppId!);
  }

  @override
  void onClose() {
    super.onClose();
    admin?.close();
  }

}

class GVItem {
  String name;
  String imgUrl;
  String? icon;
  Function(GVItem item, int index)? onTap;

  GVItem(this.name, this.imgUrl, {this.icon, this.onTap});
}
